'use strict';

const Service = require('egg').Service;
const Mock = require('mockjs')

class knowledgeService extends Service {
    async getList() {
        const {
            ctx,
            app
        } = this;
        // // 模拟数据插入表中
        // const {list} = Mock.mock({
        //     "list|5":[
        //         {
        //             name:"@ctitle(4,8)",
        //             connect:"@ctitle(4,20)",
        //             url:'@image(200x100,@color)',
        //         }
        //     ]            
        // });
        // // 循环list
        // list.forEach((item)=>{
        //     app.mysql.insert('knowledge',{...item});
        // });
        // return 'ok'
        const {
            pageSize,
            pageIndex,
            name,
        } = ctx.query;
        let sql = `select * from knowledge where 1=1 `;
        let countSql = `select count(id) as total from knowledge where 1=1 `
        if (name) {
            sql += `and name like "%${name}%" `
            countSql += `and name like "%${name}%" `
        }
        if (pageSize && pageIndex) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        const res = await app.mysql.query(sql);
        const [{
            total
        }] = await app.mysql.query(countSql);
        return {
            data: res,
            total,
        }
    }
    // 获取知识小册详情
    async getDetail(){
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.params;
        const res = await app.mysql.get('knowledge', {
            id
        })
        // 让访问量+1
        await app.mysql.update('knowledge', {
            id,
            read_num: ++res.read_num
        })
        return res
    }
}

module.exports = knowledgeService;